package org.fle4y.example.aio.sendfile;

import java.io.File;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.FileChannel;
import java.nio.file.StandardOpenOption;
import java.util.Properties;
import java.util.concurrent.Future;
import java.util.logging.Logger;

import org.fle4y.common.utils.log.LogUtil;

/**
 * author : xiehui<br>
 * company : northking <br>
 * Create at: 2012-6-10<br>
 * @version : 1.0<br>
 * mailto:flexie@foxmail.com<br>
 *  Description : 文件传输客户端
 */
@SuppressWarnings("unchecked")
public class FlieClient {
	private static final  Logger log =LogUtil.getLogger(FlieClient.class.getName());
	public static void main(String[] args) throws Exception{
		Properties props = new Properties();
		props.load(FlieClient.class.getResourceAsStream("file.ini"));
		File file =new File(props.getProperty("filepath"));
		AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
		Future future = client
				.connect(new InetSocketAddress("localhost", 8888));
		future.get();
		FileChannel fc = FileChannel.open(file.toPath(),
				StandardOpenOption.READ);
		ByteBuffer readBuf = ByteBuffer.allocate(1024);
		int total = 0;
		int result = 0;
		log.info("开始上传文件.");
		while ((result = fc.read(readBuf)) > 0) {
			total += result;
			readBuf.flip();
			client.write(readBuf).get();
			readBuf.clear();
			log.info("Read Data Size :"+result);
		}
		log.info("上传文件结束.");
		client.close();
	}
}
